/**
 * @author gaoyj on 2018/8/1.
 */
var batchIds = [];
var ids = [];
var myDate = new Date();
var month = myDate.getMonth() + 1;
var day = myDate.getDate();
if (month < 10) {
    month = "0" + month;
}
if (day < 10) {
    day = "0" + day;
}
var _start = formatDateDay(myDate, 4) + " 00:00:00";
var _end = myDate.getFullYear() + '-' + month + '-' + day + " 23:59:59";
$(function () {
    buttonShiro("export_Role");
    $.ajax({
        type: "POST",
        url: "/CardProductController/queryAllCardOperatorList",
        dataType: "json",
        success: function (data) {
            $("#operator").html("");
            var str = "<option value=\"\">全部</option>";
            if (data != null && data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    str += '<option value=' + data[i].cardOperatorId + '>' + data[i].cardOperatorName + '</option>'
                }
            }
            $("#operator").append(str);
            //缺一不可  
            $('.selectpicker').selectpicker('refresh');
            $('.selectpicker').selectpicker('render');
        },
        beforeSend: function () {
        }
    });
})

function formatDateDay(date, index) {
    date = new Date(date - index * 24 * 60 * 60 * 1000);
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    return year + "-" + month + "-" + day;
}

$("#buyStartTime").val(_start);
$("#buyEndTime").val(_end);
laydate.render({
    elem: '#buyStartTime',
    type: 'datetime'

});
laydate.render({
    elem: '#buyEndTime'
    , type: 'datetime'
});
getTelecomJudge()
$('#dataTable').bootstrapTable({
    url: '/xianyuDetail/queryReceiveList',
    height: $(window).height() - 200,
    pageSize: 100,
    pagination: true,
    pageList: [30, 50, 100],
    clickToSelect: true,
    queryParams: queryParams,
    uniqueId: 'id',
    queryParamsType: '',
    sidePagination: 'server',
    responseHandler: function (res) {
        return {
            "total": res.total,//总页数
            "rows": res.resultList   //数据
        };
    },
    columns: [[
        {
            checkbox: true,
            align: 'center'
        }, {
            width: '3px',
            align: 'center',
            formatter: function (v, row, index) {
                return index + 1
            }
        }, {
            field: 'batchId',
            title: '批次号/订单号/茶蛋订单号',
            width: 200,
            align: 'center',
            formatter: function (v, r) {
                return '<span>' + v + '</span>' + '</br><span>' + r.orderId + '</span>' + '</br><span>' + (r.teeEggOrderNo == null ? "" : r.teeEggOrderNo) + '</span>';
            }
        },
        {
            field: 'zfbOrderId',
            title: '支付宝流水号',
            width: 90, align: 'center',
            formatter: function (v, o) {
                var zfbOrderId = o.zfbOrderId;
                if (zfbOrderId === undefined || zfbOrderId === "" || zfbOrderId === null) {
                    zfbOrderId = "-";
                }
                return zfbOrderId;
            }
        }, {
            field: 'status',
            title: '运营商/状态',
            width: 90, align: 'center',
            formatter: function (v, o) {
                return (o.cardOperatorName == null ? "-" : o.cardOperatorName) + "</br>" + convertStatus(v);
            }
        }, {
            field: 'orderStatus',
            title: '闲鱼状态',
            width: 50,
            align: 'center',
            formatter: function (v, row, index) {
                return xianyuOrderStatus(v)
            }
        },
        {
            field: 'productName',
            title: '产品名称',
            width: 50,
            align: 'center'
        }, {
            field: 'face',
            title: '面 值',
            width: 50,
            align: 'center'
        }, {
            field: 'discount',
            title: '折-扣',
            width: 50,
            align: 'center',
            formatter: function (v, o) {
                if (o.productType > 310) {
                    return "1";
                } else {
                    return v;
                }
            }
        }, {
            field: 'settlePrice',
            title: '销卡面值',
            width: 60,
            align: 'center', formatter: function (v, o) {
                if (o.productType > 310) {
                    return o.equitySettlePrice;
                } else {
                    return v;
                }
            }
        },
        {
            field: 'userPrice',
            title: '结算金额',
            width: 60,
            align: 'center',
            formatter: function (v, o) {
                if (o.productType > 310) {
                    if (o.status != 1) {
                        return "0";
                    } else {
                        return o.equityUserPrice;
                    }
                } else {
                    return v;
                }
            }
        }, {
            field: 'commission',
            title: '佣金',
            width: 90, align: 'center'
        }, {
            field: 'channel',
            title: '订单来源',
            width: 90, align: 'center',
            formatter: function (v, o) {
                return o.channel == 1 ? "茶蛋" : "闲鱼";
            }
        },
        {
            field: 'cardNumber',
            title: '卡号/卡密',
            width: 200, align: 'center',
            formatter: function (v, o) {
                var resultStr = "";
                var num = "'" + o.cardNumber + "'"
                if (o.maintenance == 1) {
                    if (o.cardNumber.length > 0 && o.productType == 3) {
                        resultStr = '<a  style="color: red" href="#" onclick="getTeleComCardStatus(' + num + ')">' + o.cardNumber + '</a>' +
                            '</br><span style="color: red" id="' + o.cardNumber + '"></span>';
                    } else {
                        resultStr = '<span style="color: red">' + o.cardNumber + '</span>'
                    }
                } else {
                    if (o.cardNumber.length > 0 && o.productType == 3) {
                        resultStr = '<a  href="#" onclick="getTeleComCardStatus(' + num + ')">' + o.cardNumber + '</a></br><span style="color: red" id="' + o.cardNumber + '"></span>';
                    } else {
                        resultStr = '<span>' + o.cardNumber + '</span>'
                    }
                }
                if (o.cardPwd != "") {
                    return resultStr + " </br>" + o.cardPwd;
                } else {
                    return resultStr
                }
            }
        },
        {
            field: 'sellerPhone',
            title: '姓名/电话',
            width: 50,
            align: 'center',
            formatter: function (v, r, index) {
                return '<span>' + r.sellerRealName + '</span>' + '</br><span>' + v + '</span>';
            }
        },
        {
            field: 'startTime',
            title: '时 间',
            width: 230,
            align: 'center',
            formatter: function (v, o) {
                return "收卡:" + o.startTime + "<br/>" +
                    "销卡:" + o.endTime + "<br/>" +
                    "失效:" + getEffect(o.effectTime);
            }
        }, {
            field: 'added',
            title: '补结算',
            width: 40,
            align: 'center',
            formatter: function (v, o) {
                if (v == 1) {
                    return "是"
                } else {
                    return "否"
                }
            }
        },
        {
            field: 'failReason',
            title: '备注',
            width: 100,
            align: 'center',
            formatter: function (v, o) {
                if ((/^[0-9]+$/.test(v))) {
                    return _getCardFailReason(v);
                } else {
                    return v;
                }
            }
        }
    ]]
});
$("#search").click(function () {
    var timeAdd = new Date($("#buyStartTime").val());
    var timeEnd = new Date($("#buyEndTime").val());
    if (timeAdd > timeEnd) {
        layer.msg("开始时间不能大于结束时间");
        return false;
    }
    var require = (timeEnd - timeAdd) / (1 * 24 * 60 * 60 * 1000);
    if (require > 7) {
        layer.msg("时间间隔不能超过7天");
        return;
    }
    $("#dataTable").bootstrapTable("refresh");
});

$("#fixProductId").click(function () {
    var timeAdd = new Date($("#buyStartTime").val());
    var timeEnd = new Date($("#buyEndTime").val());
    if (timeAdd > timeEnd) {
        layer.msg("开始时间不能大于结束时间");
        return false;
    }
    var require = (timeEnd - timeAdd) / (1 * 24 * 60 * 60 * 1000);
    if (require > 7) {
        layer.msg("时间间隔不能超过7天");
        return;
    }
    $.confirm({
        title: '确认!',
        content: '确定查询订单产品名称？',
        confirm: function () {
            $.ajax({
                type: "POST",
                url: "/xianyuDetail/fixProductId",
                traditional: true,
                data: {
                    startTime: $("#buyStartTime").val(),
                    endTime: $("#buyEndTime").val()
                },
                dataType: "json",
                success: function (data) {
                    if (data.success) {
                        $("#dataTable").bootstrapTable("refresh");
                        layer.msg(data.message);
                    } else {
                        layer.msg(data.message)
                    }
                },
                beforeSend: function () {
                }
            });
        },
        cancel: function () {

        }
    });
});

function getEffect(value) {
    return value.substring(0, 4) + "-" + value.substring(4, 6) + "-" + value.substring(6, 8) + " " + value.substring(8, 10) + ":" + value.substring(10, 12) + ":" + value.substring(12, 14)
}

//同步
$("#synchronous").click(function () {
    batchIds = [];
    ids = [];
    var rows = $('#dataTable').bootstrapTable("getSelections");
    if (rows == null || rows.length === 0) {
        layer.msg("请选择要操作的数据");
        return;
    }
    for (var i = 0; i < rows.length; i++) {
        batchIds.push(rows[i].batchId);
        ids.push(rows[i].id);
    }
    $.confirm({
        title: '确认!',
        content: '确定同步？',
        confirm: function () {
            $.ajax({
                type: "POST",
                url: "/xianyuDetail/synchronousCard",
                traditional: true,
                data: {
                    ids: ids
                },
                dataType: "json",
                success: function (data) {
                    if (data.success) {
                        $("#dataTable").bootstrapTable("refresh");
                        layer.msg(data.message);
                    } else {
                        layer.msg(data.message)
                    }
                },
                beforeSend: function () {
                }
            });
        },
        cancel: function () {

        }
    });
})
$("#autoAsyn").click(
    function () {
        var rows = $('#dataTable').bootstrapTable("getSelections");
        if (rows == null || rows.length === 0) {
            layer.msg("请选择要操作的数据");
            return;
        }
        var row = rows[0];
        $.confirm({
            title: '确认!',
            content: '确定手动异步' + row.cardNumber + '吗？',
            confirm: function () {
                $.post("/xianyuDetail/orderAsyn?orderId="
                    + row.orderId, function (data) {
                    layer.msg(data.message);
                });
            },
            cancel: function () {

            }
        });
    });
//下载
$("#export").click(function () {
    var timeAdd = new Date($("#buyStartTime").val());
    var timeEnd = new Date($("#buyEndTime").val());
    var require = (timeEnd - timeAdd) / (1 * 24 * 60 * 60 * 1000);
    if (require > 1) {
        layer.msg("只能下载一天的数据");
        return;
    }
    window.location.href = "/xianyuDetail/downLoad?" + $("#buyCode").serialize()
})

function queryParams(params) {
    var statusStr = $("#status").val();
    if (statusStr != null) {
        statusStr = $("#status").val().join(',');
    }
    return {
        productType: $('#operator').val(),
        cardNumber: $.trim($('#cardNumber').val()),
        userAccount: $.trim($('#userAccount').val()),
        page: params.pageNumber,
        size: params.pageSize,
        startTime: $("#buyStartTime").val(),
        endTime: $("#buyEndTime").val(),
        batchId: $.trim($("#batch").val()),
        statusStr: statusStr,
        face: $.trim($("#face").val()),
        channel: $.trim($("#channel").val()),
        timeType: $("#timeType").val()
    };
}

//批次失败 卡号失败 批次再次提交
function failFun(v) {
    batchIds = [];
    ids = [];
    var rows = $('#dataTable').bootstrapTable("getSelections");
    if (rows == null || rows.length === 0) {
        layer.msg("请选择要操作的数据");
        return;
    }
    for (var i = 0; i < rows.length; i++) {
        batchIds.push(rows[i].batchId);
        ids.push(rows[i].id);
    }
    var title = "";
    switch (v) {
        case 1:
            title = "批次失败";
            ids = [];
            break;
        case 2:
            title = "卡号失败";
            batchIds = [];
            break;
        case 3:
            title = "批次再次提交";
            ids = [];
            break;
    }
    $.confirm({
        title: '确认!',
        content: '确定' + title + "？",
        confirm: function () {
            $.ajax({
                type: "POST",
                url: "/xianyuDetail/setFail",
                traditional: true,
                data: {
                    batchId: batchIds,
                    operate: v,
                    id: ids
                },
                dataType: "json",
                success: function (data) {
                    if (data.success) {
                        $("#dataTable").bootstrapTable("refresh");
                        layer.msg(data.message);
                    } else {
                        layer.msg(data.message)
                    }
                },
                beforeSend: function () {
                }
            });
        },
        cancel: function () {

        }
    });
}

function equityToFail() {
    ids = [];
    var rows = $('#dataTable').bootstrapTable("getSelections");
    if (rows == null || rows.length === 0) {
        layer.msg("请选择要操作的数据");
        return;
    }
    var status = rows[0].status;
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].status != 3 && rows[i].status != 1 && rows[i].status != 10 && rows[i].status != 9) {
            layer.msg("仅可售、已售、待结算、纠纷中订单可以置失败");
            return
        }
        if (rows[i].status != status) {
            layer.msg("不可操作不同状态的订单");
            return
        }
        ids.push(rows[i].id);
    }
    $("#updateUserCertificateModal").modal("show");
}

function equitySetFail() {
    ids = [];
    var rows = $('#dataTable').bootstrapTable("getSelections");
    if (rows == null || rows.length === 0) {
        layer.msg("请选择要操作的数据");
        return;
    }
    var status = rows[0].status;
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].productType <= 310) {
            layer.msg("仅操作权益订单");
            return
        }
        if (rows[i].status != 3 && rows[i].status != 1 && rows[i].status != 10 && rows[i].status != 9) {
            layer.msg("仅可售、已售、待结算、纠纷中订单可以置失败");
            return
        }
        if (rows[i].status != status) {
            layer.msg("成功订单不可与其他状态订单同时操作");
            return
        }
        ids.push(rows[i].id);
    }
    var url;
    if (status == 3 || status == 10 || status == 9) {
        url = "/xianyuDetail/equitySetFail";
    } else if (status == 1) {
        url = "/xianyuDetail/equitySuccessToFail";
    }
    $.confirm({
        title: '确认!',
        content: '确定将这些订单置失败吗？',
        confirm: function () {
            $.ajax({
                type: "POST",
                url: url,
                traditional: true,
                data: {
                    ids: ids,
                    remark: $("#remark").val()
                },
                dataType: "json",
                success: function (data) {
                    if (data.success) {
                        $("#dataTable").bootstrapTable("refresh");
                        $("#updateUserCertificateModal").modal("hide");
                        layer.msg(data.message);
                    } else {
                        $("#updateUserCertificateModal").modal("hide");
                        layer.msg(data.message)
                    }
                },
                beforeSend: function () {
                }
            });
        },
        cancel: function () {

        }
    });
}

function equitySetSuccess() {
    ids = [];
    var rows = $('#dataTable').bootstrapTable("getSelections");
    if (rows == null || rows.length === 0) {
        layer.msg("请选择要操作的数据");
        return;
    }
    var status = rows[0].status;
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].productType <= 310) {
            layer.msg("仅可操作权益订单");
            return
        }
        if (rows[i].status != 0 && rows[i].status != 9 && rows[i].status != 10) {
            layer.msg("仅在售、待结算、纠纷中订单可以置成功");
            return
        }
        if (rows[i].status != status) {
            layer.msg("不可操作不同状态的订单");
            return
        }
        ids.push(rows[i].id);
    }
    $.confirm({
        title: '确认!',
        content: '确定将这些订单置成功吗？',
        confirm: function () {
            $.ajax({
                type: "POST",
                url: "/xianyuDetail/equitySetSuccess",
                traditional: true,
                data: {
                    ids: ids
                },
                dataType: "json",
                success: function (data) {
                    if (data.success) {
                        $("#dataTable").bootstrapTable("refresh");
                        layer.msg(data.message);
                    } else {
                        layer.msg(data.message)
                    }
                },
                beforeSend: function () {
                }
            });
        },
        cancel: function () {

        }
    });
}

function getTeleComCardStatus(cardId) {
    var ret = "未知   ";
    var url = '/xianyuDetail/getTeleComCardStatus?cardId=' + cardId
    console.log(url)
    $.ajax({
        url: url,
        cache: false,
        async: false,
        type: "GET",
        dataType: 'text',
        success: function (status) {
            ret = status;
        },
        error: function (xhr) {
            alert('错误\n\n' + xhr.responseText)
        }
    });
    $("#" + cardId).html(ret)
}

//停止/开启电信预判异常直接走试充
$('#changeTelecomJudge').click(function (e) {
    var status;
    e.stopPropagation();
    var remind = "";
    var isOn = $('#include2').prop('checked');
    if (isOn) {
        remind = "异常n次走试充";
        status = 0
    } else {
        remind = "直接走试充"
        status = 1
    }
    $.confirm({
        title: '确认!',
        content: '确定要' + remind + '吗？',
        confirm: function () {
            $.ajax({
                type: "POST",
                url: "/xianyuDetail/changeTelecomJudge",
                data: {
                    status: status
                },
                dataType: "json",
                success: function (data) {
                    if (data.success) {
                        layer.msg(data.message);
                        getTelecomJudge();
                    } else {
                        layer.msg(data.message);
                        getTelecomJudge();
                    }
                }
            })
        }
    })
})

function getTelecomJudge() {
    $.ajax({
        type: "POST",
        url: "/xianyuDetail/getTelecomJudge",
        success: function (data) {
            if (data) {
                $('#include2').bootstrapToggle('on');
            } else {
                $('#include2').bootstrapToggle('off');
            }
        }
    });
}